<template> 
  <div>
    <el-upload
      :action="localUploadUrl"
      :data="moduleData"
      list-type="picture"
      :multiple="false"
      :headers="headers"
      :show-file-list="showFileList"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview">
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB
      <span v-if="prcScaleValue">，推荐图片比例：{{prcScaleValue}}</span>
    </div>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="fileList[0].url" alt="">
    </el-dialog>
  </div>
</template>
<script>
  import { getToken } from '@/utils/auth'

  export default {
    name: 'SingleImageUpload',
    props: {
      value: String,
      // 模块路径名称
      module: String,
      // 图片比例说明
      prcScale: String,
    },
    computed: {
      imageUrl() {
        return this.value;
      },
      imageName() {
        if (this.value != null && this.value !== '') {
          return this.value.substr(this.value.lastIndexOf("/") + 1);
        } else {
          return null;
        }
      },
      fileList() {
        return [{
          name: this.imageName,
          url: process.env.VUE_APP_FILE_URL + this.imageUrl
        }]
      },
      showFileList: {
        get: function() {
          return this.value !== null && this.value !== '' && this.value !== undefined;
        },
        set: function(newValue) {}
      }
    },
    data() {
      return {
        moduleData: {
          name: this.$props.module,
        },
        headers: {
          SalonAdminToken: getToken(),
        },
        dialogVisible: false,
        prcScaleValue: this.$props.prcScale,
        localUploadUrl: process.env.VUE_APP_BASE_API + "/local/file/upload", // 上传的图片服务器地址
      };
    },
    methods: {
      emitInput(val) {
        this.$emit('input', val)
      },
      handleRemove(file, fileList) {
        this.emitInput('');
      },
      handlePreview(file) {
        this.dialogVisible = true;
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG | PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      handleUploadSuccess(res, file) {
        this.showFileList = true;
        this.fileList.pop();
        this.fileList.push({
          name: file.name,
          url: process.env.VUE_APP_FILE_URL + res.type + "/" + res.realName
        });
        let filePath = res.type + "/" + res.realName;
        this.emitInput(filePath);
      }
    }
  }
</script>
